package com.org.api.support.interceptors;

import com.org.platform.utils.CommonUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author duheng
 * @Date 2021/11/13 17:00
 */
@Slf4j
@Component
public class AdminApiInterceptor implements HandlerInterceptor {

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String token = request.getHeader("token");
		String loginName = request.getHeader("loginName");
		log.info("loginName:{},token:{}", loginName, token);
		if (CommonUtil.isNullOrEmpty(token) || CommonUtil.isNullOrEmpty(loginName)) {
			response.sendRedirect(request.getContextPath() + "/error/401");
			return false;
		}
		if (!stringRedisTemplate.hasKey(loginName)) {
			log.info("mobile:{} token expire", loginName);
			response.sendRedirect(request.getContextPath() + "/error/401");
			return false;
		}
		String tokenValue = stringRedisTemplate.opsForValue().get(loginName);
		if (!CommonUtil.equals(token, tokenValue)) {
			response.sendRedirect(request.getContextPath() + "/error/401");
			return false;
		}
		return true;
	}
}
